/**
 * 数据统计脚本
 */

// ECharts实例
let appointmentTrendChart = null;
let appointmentStatusChart = null;
let vaccineTypeChart = null;
let siteAppointmentChart = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态和权限
    if (!Auth.isLoggedIn()) {
        window.location.href = '../login.html';
        return;
    }

    if (!Auth.checkRole(UserRole.SUPER_ADMIN)) {
        UI.showMessage('您没有权限访问此页面', 'danger');
        setTimeout(() => {
            Auth.logout();
        }, 2000);
        return;
    }

    // 初始化页面
    initPage();
});

/**
 * 初始化页面
 */
async function initPage() {
    // 显示用户信息
    displayUserInfo();
    
    // 初始化图表
    initCharts();
    
    // 加载统计数据
    await loadStatistics();
}

/**
 * 显示用户信息
 */
function displayUserInfo() {
    const userInfo = Auth.getUserInfo();
    if (userInfo) {
        const userName = document.getElementById('userName');
        const userAvatar = document.getElementById('userAvatar');
        
        if (userName) userName.textContent = userInfo.account || '超级管理员';
        if (userAvatar) userAvatar.textContent = (userInfo.account || 'S').charAt(0).toUpperCase();
    }
}

/**
 * 初始化图表
 */
function initCharts() {
    // 预约趋势图表
    appointmentTrendChart = echarts.init(document.getElementById('appointmentTrendChart'));
    
    // 预约状态分布图表
    appointmentStatusChart = echarts.init(document.getElementById('appointmentStatusChart'));
    
    // 疫苗类型分布图表
    vaccineTypeChart = echarts.init(document.getElementById('vaccineTypeChart'));
    
    // 接种点预约统计图表
    siteAppointmentChart = echarts.init(document.getElementById('siteAppointmentChart'));
    
    // 窗口大小改变时重新调整图表
    window.addEventListener('resize', function() {
        appointmentTrendChart.resize();
        appointmentStatusChart.resize();
        vaccineTypeChart.resize();
        siteAppointmentChart.resize();
    });
}

/**
 * 加载统计数据
 */
async function loadStatistics() {
    try {
        UI.showLoading();
        
        // 加载系统概览数据
        const overviewData = await HttpClient.get('/admin/statistics/overview');
        updateOverviewStats(overviewData);
        
        // 加载预约趋势数据（最近30天）
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - 29); // 最近30天
        
        const startDateStr = `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}-${String(startDate.getDate()).padStart(2, '0')}`;
        const endDateStr = `${endDate.getFullYear()}-${String(endDate.getMonth() + 1).padStart(2, '0')}-${String(endDate.getDate()).padStart(2, '0')}`;
        
        const trendData = await HttpClient.get(`/admin/statistics/appointment-trend?startDate=${startDateStr}&endDate=${endDateStr}`);
        renderAppointmentTrendChart(trendData);
        
        // 渲染其他图表（使用概览数据）
        renderAppointmentStatusChart(overviewData);
        renderVaccineTypeChart();
        renderSiteAppointmentChart();
        
        UI.hideLoading();
    } catch (error) {
        console.error('加载统计数据失败:', error);
        UI.hideLoading();
        UI.showMessage('加载数据失败: ' + error.message, 'danger');
    }
}

/**
 * 更新概览统计
 */
function updateOverviewStats(data) {
    if (data.totalUsers !== undefined) {
        document.getElementById('totalUsers').textContent = data.totalUsers;
    }
    if (data.totalAppointments !== undefined) {
        document.getElementById('totalAppointments').textContent = data.totalAppointments;
    }
    if (data.totalSites !== undefined) {
        document.getElementById('totalSites').textContent = data.totalSites;
    }
    if (data.totalVaccines !== undefined) {
        document.getElementById('totalVaccines').textContent = data.totalVaccines;
    }
}

/**
 * 渲染预约趋势图表
 */
function renderAppointmentTrendChart(data) {
    // 处理数据：后端返回的是 AppointmentTrendVO 数组
    let dates = [];
    let counts = [];
    let completedCounts = [];
    let cancelledCounts = [];
    
    if (data && Array.isArray(data) && data.length > 0) {
        dates = data.map(item => {
            // 格式化日期为 MM-DD
            if (item.date) {
                const date = new Date(item.date);
                return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
            }
            return '';
        });
        counts = data.map(item => item.appointmentCount || 0);
        completedCounts = data.map(item => item.completedCount || 0);
        cancelledCounts = data.map(item => item.cancelledCount || 0);
    } else {
        // 如果没有数据，显示最近30天的空图表
        const today = new Date();
        for (let i = 29; i >= 0; i--) {
            const date = new Date(today);
            date.setDate(date.getDate() - i);
            dates.push(`${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`);
            counts.push(0);
            completedCounts.push(0);
            cancelledCounts.push(0);
        }
    }
    
    const option = {
        title: {
            text: '近30天预约趋势',
            left: 'center',
            textStyle: {
                fontSize: 16
            }
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                let result = params[0].axisValue + '<br/>';
                params.forEach(param => {
                    result += param.marker + param.seriesName + ': ' + param.value + '<br/>';
                });
                return result;
            }
        },
        legend: {
            data: ['预约数量', '已完成', '已取消'],
            top: 30
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: dates,
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            name: '预约数量'
        },
        series: [
            {
                name: '预约数量',
                type: 'line',
                data: counts,
                smooth: true,
                itemStyle: {
                    color: '#4A90E2'
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [{
                            offset: 0, color: 'rgba(74, 144, 226, 0.3)'
                        }, {
                            offset: 1, color: 'rgba(74, 144, 226, 0.05)'
                        }]
                    }
                }
            },
            {
                name: '已完成',
                type: 'line',
                data: completedCounts,
                smooth: true,
                itemStyle: {
                    color: '#52c41a'
                }
            },
            {
                name: '已取消',
                type: 'line',
                data: cancelledCounts,
                smooth: true,
                itemStyle: {
                    color: '#f5222d'
                }
            }
        ]
    };
    
    appointmentTrendChart.setOption(option);
}

/**
 * 渲染预约状态分布图表
 */
function renderAppointmentStatusChart(data) {
    const chartData = [
        { value: data.pendingAppointments || 0, name: '待接种', itemStyle: { color: '#faad14' } },
        { value: data.completedAppointments || 0, name: '已完成', itemStyle: { color: '#52c41a' } },
        { value: data.cancelledAppointments || 0, name: '已取消', itemStyle: { color: '#f5222d' } }
    ];
    
    // 如果没有任何数据
    const total = chartData.reduce((sum, item) => sum + item.value, 0);
    if (total === 0) {
        appointmentStatusChart.setOption({
            title: {
                text: '暂无预约数据',
                left: 'center',
                top: 'center',
                textStyle: {
                    color: '#999',
                    fontSize: 14
                }
            },
            series: []
        });
        return;
    }
    
    const option = {
        title: {
            text: '预约状态分布',
            left: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            top: 'middle'
        },
        series: [
            {
                name: '预约状态',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['60%', '50%'],
                avoidLabelOverlap: false,
                label: {
                    show: true,
                    position: 'outside',
                    formatter: '{b}: {c}'
                },
                labelLine: {
                    show: true
                },
                data: chartData,
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    
    appointmentStatusChart.setOption(option);
}

/**
 * 渲染疫苗类型分布图表
 */
async function renderVaccineTypeChart() {
    try {
        // 获取疫苗列表统计
        const vaccines = await HttpClient.get('/admin/vaccine/list?pageNum=1&pageSize=1000');
        
        // 统计各类型疫苗数量
        const typeCount = {};
        if (vaccines.records) {
            vaccines.records.forEach(vaccine => {
                const typeName = Format.vaccineType(vaccine.type);
                typeCount[typeName] = (typeCount[typeName] || 0) + 1;
            });
        }
        
        const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4'];
        const chartData = Object.keys(typeCount).map((key, index) => ({
            value: typeCount[key],
            name: key,
            itemStyle: { color: colors[index % colors.length] }
        }));
        
        // 如果没有数据
        if (chartData.length === 0) {
            vaccineTypeChart.setOption({
                title: {
                    text: '暂无疫苗数据',
                    left: 'center',
                    top: 'center',
                    textStyle: {
                        color: '#999',
                        fontSize: 14
                    }
                },
                series: []
            });
            return;
        }
        
        const option = {
            title: {
                text: '疫苗类型分布',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                top: 'middle'
            },
            series: [
                {
                    name: '疫苗类型',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    center: ['60%', '50%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: true,
                        position: 'outside',
                        formatter: '{b}: {c}'
                    },
                    labelLine: {
                        show: true
                    },
                    data: chartData,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        
        vaccineTypeChart.setOption(option);
    } catch (error) {
        console.error('加载疫苗类型统计失败:', error);
        vaccineTypeChart.setOption({
            title: {
                text: '加载失败',
                left: 'center',
                top: 'center',
                textStyle: {
                    color: '#f5222d',
                    fontSize: 14
                }
            },
            series: []
        });
    }
}

/**
 * 渲染接种点预约统计图表
 */
async function renderSiteAppointmentChart() {
    try {
        // 获取接种点列表（使用正确的API路径）
        const sitesResponse = await HttpClient.get('/vaccinationsite/list');
        const sites = sitesResponse && Array.isArray(sitesResponse) ? sitesResponse : [];
        
        if (!sites || sites.length === 0) {
            siteAppointmentChart.setOption({
                title: {
                    text: '暂无接种点数据',
                    left: 'center',
                    top: 'center',
                    textStyle: {
                        color: '#999',
                        fontSize: 14
                    }
                },
                series: []
            });
            return;
        }
        
        // 获取每个接种点的预约统计
        const siteStats = [];
        for (const site of sites) {
            try {
                const stats = await HttpClient.get(`/admin/statistics/site/${site.id}`);
                if (stats && stats.totalAppointments !== undefined) {
                    siteStats.push({
                        name: site.name || '未知接种点',
                        count: stats.totalAppointments || 0
                    });
                } else {
                    siteStats.push({
                        name: site.name || '未知接种点',
                        count: 0
                    });
                }
            } catch (error) {
                // 如果获取某个接种点统计失败，使用0
                siteStats.push({
                    name: site.name || '未知接种点',
                    count: 0
                });
            }
        }
        
        const siteNames = siteStats.map(s => s.name);
        const appointmentCounts = siteStats.map(s => s.count);
        
        const option = {
            title: {
                text: '接种点预约统计',
                left: 'center',
                textStyle: {
                    fontSize: 16
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function(params) {
                    const param = params[0];
                    return param.name + '<br/>' + param.marker + param.seriesName + ': ' + param.value;
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                top: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: siteNames,
                axisLabel: {
                    interval: 0,
                    rotate: 30,
                    fontSize: 12
                }
            },
            yAxis: {
                type: 'value',
                name: '预约数量'
            },
            series: [
                {
                    name: '预约数量',
                    type: 'bar',
                    data: appointmentCounts,
                    itemStyle: {
                        color: function(params) {
                            // 根据数值大小使用不同颜色
                            const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4'];
                            return colors[params.dataIndex % colors.length];
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}'
                    }
                }
            ]
        };
        
        siteAppointmentChart.setOption(option);
    } catch (error) {
        console.error('加载接种点统计失败:', error);
        siteAppointmentChart.setOption({
            title: {
                text: '加载失败',
                left: 'center',
                top: 'center',
                textStyle: {
                    color: '#f5222d',
                    fontSize: 14
                }
            },
            series: []
        });
    }
}

/**
 * 退出登录
 */
function handleLogout() {
    UI.confirm('确定要退出登录吗？', () => {
        Auth.logout();
    });
}

